package app.framework.controller.common;

import app.framework.auth.AuthService;
import app.framework.controller.base.BaseController;
import app.framework.security.jwt.JwtUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
public class AuthController extends BaseController {
    @Value("${jwt.header}")
    private String header;
    @Value("${jwt.tokenHead}")
    private String tokenHeader;

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping(value = "/authenticate", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Map authenticate(@RequestBody JSONObject authObject) throws AuthenticationException{
        Preconditions.checkNotNull(authObject);
        final String token = authService.login(authObject.getString("username"),authObject.getString("password"));
        return toMap(token);
    }

    @RequestMapping(value = "/tokenrefresh", method = RequestMethod.GET)
    public ResponseEntity<?> refresh(HttpServletRequest request) throws AuthenticationException{
        String token = request.getHeader(header).substring(tokenHeader.length());
        String refreshedToken = authService.refresh(token);
        if(refreshedToken == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid token!!");
        } else {
            return ResponseEntity.ok(toMap(refreshedToken));
        }
    }

    @RequestMapping(value = "/me", method = RequestMethod.GET)
    public String me() throws AuthenticationException {
        return toJson(getCurrentUser());
    }

    /**
     * 将token转换成map，便于json形式返回
     * @param token
     * @return
     */
    private Map toMap(String token) {
        Map map = Maps.newHashMap();
        map.put("token", token);
        return map;
    }
}
